package com.example.afinal;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class RateActivity extends AppCompatActivity implements Runnable{

    private static final String TAG = "RateActivity";
    private float dollarRate = 12.3f;
    private float euroRate = 23.4f;
    private float wonRate = 345.6f;

    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);

        SharedPreferences sharedPreferences = getSharedPreferences("myrate",Activity.MODE_PRIVATE);

        dollarRate = sharedPreferences.getFloat("dollar_rate",0.0f);
        euroRate = sharedPreferences.getFloat("euro_rate",0.0f);
        wonRate = sharedPreferences.getFloat("won_rate",0.0f);

        Log.i(TAG,"onCreate: sp dollarRate=" + dollarRate);
        Log.i(TAG,"onCreate: sp euroRate=" + euroRate);
        Log.i(TAG,"onCreate: sp wonRate=" + wonRate);


        Thread t = new Thread(this);
        t.start();
        Log.i(TAG,"onCreate: t.start().....");

        handler = new Handler(Looper.myLooper()){
          @Override
          public void handleMessage(@NonNull Message msg){
              Log.i(TAG,"handleMessage: 收到消息：" + msg.what);
              if (msg.what==6){
                  Log.i(TAG,"handleMessage: 内容：" + msg.obj);
                  Toast.makeText(RateActivity.this,"收到:" + msg.obj,Toast.LENGTH_SHORT).show();
              }
              super.handleMessage(msg);
          }
        };

//        Thread t2 = new Thread(()->{
//
//        });
//        t2.start();

    }

    public void click01(View btn)
    {
        EditText rmb = findViewById(R.id.rmb);
        String inputStr = rmb.getText().toString();
        if(inputStr.length()==0)
        {
            Toast.makeText(this,"请输入金额后再计算",Toast.LENGTH_SHORT).show();
        }
        float rmbf = Float.parseFloat(inputStr);
        float r = rmbf * dollarRate;
        if(btn.getId() == R.id.btn2)
        {
            r = rmbf * euroRate;
        }else if(btn.getId() == R.id.btn3)
        {
            r = rmbf * wonRate;
        }
        TextView result = findViewById(R.id.result);
        result.setText(String.valueOf(r));
    }


    public void click02(View btn)
    {
        Intent intent2 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:87092173"));;
        startActivity(intent2);
    }

    public void click03(View btn)
    {
        Intent intent2 = new Intent(Intent.ACTION_VIEW,Uri.parse("https://www.jd.com"));;
        startActivity(intent2);
    }

    public void openConfig(View btn)
    {
        Intent config = new Intent(this,ConfigActivity.class);
        config.putExtra("dollar_key",dollarRate);
        config.putExtra("euro_key",euroRate);
        config.putExtra("won_key",wonRate);

        Log.i(TAG,"openConfig: dollarRate=" + dollarRate);
        Log.i(TAG,"openConfig: euroRate=" + euroRate);
        Log.i(TAG,"openConfig: wonRate=" + wonRate);
        startActivityForResult(config,6);
    }

    @Override
    protected void onActivityResult(int requestCode,int resultCode,@Nullable Intent data)
    {
        if(requestCode==6 && resultCode==2)
        {
            Bundle bdl2 = data.getExtras();
            dollarRate = bdl2.getFloat("dollar_key2",0f);
            euroRate = bdl2.getFloat("euro_key2",0f);
            wonRate = bdl2.getFloat("won_key2",0f);

            Log.i(TAG,"onActivityResult: dollarRate=" + dollarRate);
            Log.i(TAG,"onActivityResult: euroRate=" + euroRate);
            Log.i(TAG,"onActivityResult: wonRate=" + wonRate);
        }

        super.onActivityResult(requestCode,resultCode,data);
    }

    @Override
    public void run() {
        Log.i(TAG,"run: ()..................");

        try {
            Thread.sleep(3000);
        }catch (InterruptedException e){
            throw new RuntimeException(e);
        }
        //URL url = null;
        try {
//            url = new URL("https://www.boc.cn/sourcedb/whpj/");
//            Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
//            HttpURLConnection http = (HttpURLConnection) url.openConnection();
//            InputStream in = http.getInputStream();
//
//            String html = inputStream2String(in);
//            Log.i(TAG,"run: html=" + html);

            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            Elements tables = doc.getElementsByTag("table");
            Element table2 = tables.get(1);
//            Log.i(TAG,"run: table2=" + table2);
            Elements trs = table2.getElementsByTag("tr");
            for (Element tr : trs){
                Elements tds = tr.getElementsByTag("td");
               // Log.i(TAG,"run: tds=" + tds);
                if (tds.size()>6) {
//                    if (tds.get(0).text().equals("欧元")) {
//                        String rateStr = tds.get(5).text();
//                        Log.i(TAG, "run: 欧元汇率=" + rateStr);
//                    }
                    String rname = tds.get(0).text();
                    String rateStr = tds.get(5).text();
                    Log.i(TAG,"run: " + rname + "==>" + rateStr);
                    if (rname.equals("欧元")){
                        Log.i(TAG,"run: 欧元汇率=" + rateStr);
                    }
                }
//                Element e = doc.select("body > div > div.Boc_main > div.publish > div:nth-child(3) > table > tbody > tr:nth-child(6)").first();
//                Log.i(TAG,"run: e=" + e);
            }
//            Element tr = trs.get(6);
//            Log.i(TAG,"run: trs.get6=" + tr);
//            Element td1 = tr.getElementsByTag("td").get(0);
//            Log.i(TAG,"run: td1.text=" + td1.text());

        } catch (MalformedURLException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }

        //发送数据回主线程
        Message msg = handler.obtainMessage(6);
        msg.obj = "Hello Android";
        handler.sendMessage(msg);
        Log.i(TAG,"run: msg已发送");
    }

//    private String inputStream2String(InputStream inputStream) throws IOException {
//        final int bufferSize = 1024;
//        final char[] buffer = new char[bufferSize];
//        final  StringBuilder out = new StringBuilder();
//        Reader in = new InputStreamReader(inputStream,"utf-8");
//        while (true){
//            int rsz = in.read(buffer,0,buffer.length);
//            if (rsz < 0)
//                break;
//            out.append(buffer,0,rsz);
//        }
//        return out.toString();
//    }
}